package com.glela.goods.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.glela.api.pay.wechat.component.WeChat;
import com.glela.cache.redis.RedisUtil;
import com.glela.common.util.JsonUtil;
import com.glela.common.util.LinkUtil;
import com.glela.common.util.StringUtil;
import com.glela.goods.mapper.GoodsMapper;
import com.glela.goods.mapper.GoodsNavigateMapper;
import com.glela.goods.mapper.MarketingActivitiesMapper;
import com.glela.goods.mapper.ShareGoodsMapper;
import com.glela.goods.model.GoodsNavigate;
import com.glela.goods.model.LiveShareRecord;
import com.glela.goods.model.MarketingActivities;
import com.glela.goods.model.ShareGoods;
import com.glela.goods.model.vo.ShareGoodsVo;
import com.glela.goods.model.vo.goods.GoodsVo;
import com.glela.goods.service.GoodsService;
import com.glela.goods.service.LiveShareRecordService;
import com.glela.goods.service.ShareGoodsService;
import com.glela.platform.constant.ErrorEnum;
import com.glela.platform.mapper.UserInfoMapper;
import com.glela.platform.mapper.UserMapper;
import com.glela.platform.model.BaseRestrictions;
import com.glela.platform.model.User;
import com.glela.platform.model.UserInfo;
import com.glela.platform.model.response.ResponseBaseModel;
import com.glela.platform.model.response.ResponseResultModel;
import com.glela.platform.service.BaseRestrictionsService;
import com.glela.platform.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("shareGoodsService")
@Scope("singleton")
public class ShareGoodsServiceImpl implements ShareGoodsService {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(ShareGoodsServiceImpl.class);
	@Autowired
	private GoodsService goodsService;
	@Autowired
	private UserService userService;
	@Autowired
	private ShareGoodsMapper shareGoodsMapper;
	@Autowired
	private GoodsMapper goodsMapper;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private UserInfoMapper userInfoMapper;
	@Autowired
	private BaseRestrictionsService baseRestrictionsService;
	@Autowired
	private GoodsNavigateMapper goodsNavigateMapper;
	@Autowired
	private WeChat  weChat;
	@Autowired
	private RedisUtil redisUtil;
	@Autowired
	private MarketingActivitiesMapper marketingActivitiesMapper;
	@Autowired
	private LiveShareRecordService liveShareRecordService;
	/**
	 * 根据分享的记录ID和浏览者的ID获取商品信息
	 * 
	 * @author 卫耀华
	 * @param shareId分享记录的ID
	 * @param seeUserId浏览者的ID
	 */
	@Override
	public ResponseEntity<?> getShareGoodsByShareIdAndSeeUserId(long shareId, long seeUserId) {
		ShareGoods shareGoods = shareGoodsMapper.selectShareGoodsById(shareId);
		if (shareGoods == null) {
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20403), HttpStatus.OK);
		}
		int shareUserRoleId = 0;
		int seeUserRoleId = 0;
		long shareUserId = shareGoods.getUserId();// 把这个商品分享出去的人的ID
		User shareUser = userService.getUser(shareUserId);
		if (shareUser != null) {
			shareUserRoleId = shareUser.getRoleId();
		}
		User seeUser = userService.getUser(seeUserId);
		if (seeUser != null) {
			seeUserRoleId = seeUser.getRoleId();
		}
		// 准备要返回的商品信息
		GoodsVo goodsVo = goodsService.selectGoodsById(shareGoods.getGoodId(), shareUserRoleId, seeUserRoleId);
		if (goodsVo == null) {
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20401), HttpStatus.OK);
		}
		// 构造将要通过接口返回的VO
		ShareGoodsVo vo = new ShareGoodsVo();
		vo.setId(shareGoods.getId());
		vo.setUserId(shareGoods.getUserId());
		vo.setGoodId(shareGoods.getGoodId());
		vo.setAgio(shareGoods.getAgio());
		vo.setGoodsVo(goodsVo);
		vo.setShareGoodsUserId(shareUserId);// 商品分享者用户ID
		return new ResponseEntity<>(new ResponseResultModel<ShareGoodsVo>(vo), HttpStatus.OK);
	}

	/**
	 * 添加商品分享
	 */
	@Transactional(rollbackFor = Exception.class)
	@Override
	public ResponseEntity<?> addShareGoods(long userId, long goodId, long materialId,String livePlanId) {
		if (Integer.parseInt(materialId+"") != 0) {// 素材分享，记录分享次数
			this.goodsMapper.saveMaterialOpenAndShareCount(materialId, 0, 1);
		}
		ShareGoods shareGoods = shareGoodsMapper.selectShareGoodsByUserIdAndGoodIdAndAgio(userId, goodId);
		String h5_link = this.baseRestrictionsService.getBaseRestrictionsForCache("h5_link").getName();
		BaseRestrictions imageBR = this.baseRestrictionsService.getBaseRestrictionsForCache("image_url");
		String image_url = imageBR.getName();
		int size = imageBR.getExperience();
		StringBuffer imageUrl = new StringBuffer();
		imageUrl.append(image_url);
		// 商品介绍图
		List<GoodsNavigate> goodsNavigateList = this.goodsNavigateMapper.selectGoodsNavigateByGoodId(goodId);
		if(!CollectionUtils.isEmpty(goodsNavigateList)){
			if(!StringUtil.isEmpty(goodsNavigateList.get(0).getNavigateImage())){
				imageUrl.append(goodsNavigateList.get(0).getNavigateImage());
				/*imageUrl.append("?imageView2/0/w/");
				imageUrl.append(size);
				imageUrl.append("/h/");
				imageUrl.append(size);*/
			}
		}
		StringBuffer shareURL = new StringBuffer();
		shareURL.append(h5_link);
		shareURL.append("/goods/index.html");
		Map<String, Object> map = new HashMap<>();
		if (shareGoods == null) {
			shareGoods = new ShareGoods();
			shareGoods.setUserId(userId);
			shareGoods.setGoodId(goodId);
			shareGoodsMapper.insertShareGoods(shareGoods);
			//添加成功 goods表分享次数+1
			this.goodsMapper.saveOpenAndShareCount(Integer.valueOf(goodId+""), 0, 1);
			shareGoods = shareGoodsMapper.selectShareGoodsByUserIdAndGoodIdAndAgio(userId, goodId);
		}
		map.put("shareGoodsId", shareGoods.getId());
		//分享链接 http://h5.xzhuang.com/goods/index.html?talentShareGoodId=1464&talentId=562853&goodId=1464&from=singlemessage
		shareURL.append("?talentShareGoodId=");
		shareURL.append(shareGoods.getId());
		shareURL.append("&goodId=");
		shareURL.append(goodId);
		shareURL.append("&talentId=");
		shareURL.append(userId);
		shareURL.append("&from=singlemessage");
		if (StringUtils.isNotBlank(livePlanId)){
			shareURL.append("&livePlanId="+livePlanId);
			LiveShareRecord liveShareRecord = new LiveShareRecord();
			liveShareRecord.setGoodsId((int)goodId);
			liveShareRecord.setLivePlanId(Integer.valueOf(livePlanId));
			liveShareRecord.setUserId((int)userId);
			liveShareRecord.setShareType(1);
			liveShareRecordService.add(liveShareRecord);
		}
		String shortLink = shareURL.toString();
		//暂时关闭微信长链接获取
//		try {
//			//appId 系统里面配置两个APPID，另一个用于第三方登录的，这个是用于支付的
//			WeChatTokenVo wx = weChat.getAccessToken(PayConfig.appId, PayConfig.secret);
//			shortLink = weChat.getWeChatShortLink(wx.getAccess_token(),shareURL.toString());
//		}catch (Exception e) {
//			LOGGER.error(" 获取短链接异常.....");
//		}
		
		map.put("shareUrl", LinkUtil.generateSinaShortUrl(shortLink));
		map.put("imageUrl", imageUrl);
		return new ResponseEntity<>(new ResponseResultModel<Map<String, Object>>(map), HttpStatus.OK);
	}

	/**
	 * 分享失败要删除之前插入的分享记录
	 * 
	 * @author 卫耀华
	 * @param shareId
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	@Override
	public void deleteShareInfoById(long shareId) {
		shareGoodsMapper.deleteShareGoodsById(shareId);
	}
	
	/**
	 * 添加店铺分享次数
	 */
	@Override
	public void addStoreShareCount(long userId) {
		User user = this.userMapper.selectByPrimaryKey(userId);
		UserInfo userInfo = userInfoMapper.selectUserInfoByPersion(user.getRecommendFrom());
		this.userMapper.updateUserShareCountById(userInfo.getUserId(),1);
	}
	
	/**
	 * 根据分享记录ID查询分享记录
	 */
	@Override
	public ShareGoods selectShareGoodsById(long shareGoodsId) {
		return this.shareGoodsMapper.selectShareGoodsById(shareGoodsId);
	}
	
	/**
	 * 开店组合商品分享
	 */
	@Override
	public ResponseEntity<?> shareOpenStoreGood(long userId) {
		String shareUri = this.baseRestrictionsService.getBaseRestrictionsForCache("open_store_uri").getName();
		String openStoreDesc = this.baseRestrictionsService.getBaseRestrictionsForCache("open_store_desc").getName();
		String openStoreImageUrl = this.baseRestrictionsService.getBaseRestrictionsForCache("open_store_image_url").getName();
		User user = this.userService.getUserById(userId);
		if (user.getRoleId() < 3) {
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C42003), HttpStatus.OK);
		}
//		ShareGoods shareGoods = this.shareGoodsMapper.selectShareGoodsByUserIdAndGoodIdAndAgio(userId, openStoreGoodId);
		String h5_link = this.baseRestrictionsService.getBaseRestrictionsForCache("h5_link").getName();
		BaseRestrictions imageBR = this.baseRestrictionsService.getBaseRestrictionsForCache("image_url");
		String image_url = imageBR.getName();
		int size = imageBR.getExperience();
		Map<String, Object> map = new HashMap<>();
		/*if (shareGoods == null) {
			shareGoods = new ShareGoods();
			shareGoods.setUserId(userId);
			shareGoods.setGoodId(Long.valueOf(openStoreGoodId));
			this.shareGoodsMapper.insertShareGoods(shareGoods);
			//添加成功 goods表分享次数+1
			this.goodsMapper.saveOpenAndShareCount(openStoreGoodId, 0, 1);
			shareGoods = shareGoodsMapper.selectShareGoodsByUserIdAndGoodIdAndAgio(userId, openStoreGoodId);
		}*/
		map.put("storeUserName", user.getNickName());
		StringBuffer storeUserHeaderPicture = new StringBuffer();
		if (StringUtil.isNotEmpty(user.getPicture())) {
			storeUserHeaderPicture.append(image_url);
			storeUserHeaderPicture.append(user.getPicture());
			storeUserHeaderPicture.append("?imageView2/0/w/");
			storeUserHeaderPicture.append(size);
			storeUserHeaderPicture.append("/h/");
			storeUserHeaderPicture.append(size);
		}
		map.put("storeUserHeaderPicture", storeUserHeaderPicture.toString());
		map.put("openStoreDesc", openStoreDesc);
		StringBuffer imageUrl = new StringBuffer();
		imageUrl.append(openStoreImageUrl);
		imageUrl.append("?imageView2/0/w/");
		imageUrl.append(size);
		imageUrl.append("/h/");
		imageUrl.append(size);
		map.put("imageUrl", imageUrl.toString());
		//分享链接 http://h5.xzhuang.com/goods/index.html?talentShareGoodId=1464&talentId=562853&goodId=1464&from=singlemessage
		StringBuffer shareURL = new StringBuffer();
		shareURL.append(h5_link);
		/*shareURL.append("/goods/index.html");
		shareURL.append("?talentShareGoodId=");
		shareURL.append(shareGoods.getId());
		shareURL.append("&goodId=");
		shareURL.append(openStoreGoodId);*/
		shareURL.append(shareUri);
		shareURL.append("&talentId=");
		shareURL.append(userId);
		shareURL.append("&from=singlemessage");
		map.put("shareUrl", shareURL.toString());
		String showImgs = this.baseRestrictionsService.getBaseRestrictionsForCache("open_store_show_img_list").getName();
		JSONArray array = JSONObject.parseArray(showImgs);
		map.put("bgImgs",array);
		return new ResponseEntity<>(new ResponseResultModel<Map<String, Object>>(map), HttpStatus.OK);
	}
	
	/**
	 * 活动页分享接口
	 */
	@Override
	public ResponseEntity<?> shareActivities(long userId, long activeId, String clientType) {
		Map<String, Object> map = new HashMap<>();
		User user = this.userService.getUserById(userId);
		String h5_activity_url = this.baseRestrictionsService.getBaseRestrictionsForCache("h5_activity_url").getName();
		BaseRestrictions imageBR = this.baseRestrictionsService.getBaseRestrictionsForCache("image_url");
		String image_url = imageBR.getName();
		int size = imageBR.getExperience();
		StringBuffer storeUserHeaderPicture = new StringBuffer();
		if (StringUtil.isNotEmpty(user.getPicture())) {
			if (!user.getPicture().startsWith("http")) {
				storeUserHeaderPicture.append(image_url);
				storeUserHeaderPicture.append(user.getPicture());
				storeUserHeaderPicture.append("?imageView2/0/w/");
				storeUserHeaderPicture.append(size);
				storeUserHeaderPicture.append("/h/");
				storeUserHeaderPicture.append(size);
			} else {
				storeUserHeaderPicture.append(user.getPicture());
			}
		}
		if (Long.valueOf(activeId).intValue() != 9999) {
			String activeDesc = "";//this.baseRestrictionsService.getBaseRestrictionsForCache("share_active_desc").getName();
			if (StringUtils.isBlank(redisUtil.get("market:active:"+activeId))){
				MarketingActivities marketingActivities = marketingActivitiesMapper.selectByPrimaryKey((int)activeId);
				activeDesc = marketingActivities.getText();
				try {
					redisUtil.set("market:active:"+activeId, JsonUtil.toJson(marketingActivities),120);
				} catch (IOException e) {
				}
			}else{
				MarketingActivities marketingActivities = JSONObject.parseObject(redisUtil.get("market:active:"+activeId),MarketingActivities.class);
				activeDesc = marketingActivities.getText();
			}
			String activeImageUrl = this.baseRestrictionsService.getBaseRestrictionsForCache("share_active_image_url").getName();
			StringBuffer imageUrl = new StringBuffer();
			imageUrl.append(activeImageUrl);
			imageUrl.append("?imageView2/0/w/");
			imageUrl.append(size);
			imageUrl.append("/h/");
			imageUrl.append(size);
			StringBuffer shareURL = new StringBuffer();
			shareURL.append(h5_activity_url);
			shareURL.append("id=");
			shareURL.append(activeId);
			shareURL.append("&");
			shareURL.append(clientType);
			shareURL.append("=1");
			shareURL.append("&talentId=");
			shareURL.append(userId);
			map.put("storeUserHeaderPicture", storeUserHeaderPicture.toString());
			map.put("activeDesc", activeDesc);
			map.put("storeUserName", user.getNickName());
			map.put("imageUrl", imageUrl.toString());
			map.put("shareUrl", LinkUtil.generateSinaShortUrl(shareURL.toString()));
		} else {
			String h5_link = this.baseRestrictionsService.getBaseRestrictionsForCache("h5_link").getName();
			StringBuffer imageUrl = new StringBuffer();
			imageUrl.append("zhangguijie.jpg");
			imageUrl.append("?imageView2/0/w/");
			imageUrl.append(size);
			imageUrl.append("/h/");
			imageUrl.append(size);
			StringBuffer shareURL = new StringBuffer();
			shareURL.append(h5_link + "/home/zhangguijie.html?");
			shareURL.append("id=");
			shareURL.append(activeId);
			shareURL.append("&");
			shareURL.append(clientType);
			shareURL.append("=1");
			shareURL.append("&talentId=");
			shareURL.append(userId);
			map.put("storeUserHeaderPicture", image_url + imageUrl.toString());
			map.put("activeDesc", "小铺掌柜日，回馈店主，全场佣金翻倍，让你赚到手软。");
			map.put("storeUserName", user.getNickName());
			map.put("imageUrl", imageUrl.toString());
			map.put("shareUrl", LinkUtil.generateSinaShortUrl(shareURL.toString()));
		}
		return new ResponseEntity<>(new ResponseResultModel<Map<String, Object>>(map), HttpStatus.OK);
	}
}
